package vip.zhenzicheng.algorithm.leetcode.array;

/**
 * <a href="https://leetcode.cn/problems/majority-element/">多数元素 [简单]</a>
 *
 * @author zhenzicheng
 * @date 2022-06-15 09:36
 */
public class MajorityElement_169 {

  public int majorityElement(int[] nums) {
    if (nums.length == 1) {
      return nums[0];
    }

    int curNum = nums[0];
    int count = 1; // 计数

    for (int i = 1; i < nums.length; i++) {
      if (count == 0) { // 全被抵消就需要保存新的元素
        curNum = nums[i];
        count = 1;
      } else {
        count = (curNum == nums[i] ? count + 1 : count - 1);
      }
    }
    return curNum;
  }
}
